package com.easylinkin.linkappapi.tenant.sevice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.bases.redis.util.RedisUtil;
import com.easylinkin.linkappapi.application.entity.Application;
import com.easylinkin.linkappapi.application.service.ApplicationService;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.utils.DigestUtil;
import com.easylinkin.linkappapi.deviceunit.entity.DeviceUnit;
import com.easylinkin.linkappapi.deviceunit.service.DeviceUnitService;
import com.easylinkin.linkappapi.elasticsearch.service.impl.EsBankServiceImpl;
import com.easylinkin.linkappapi.function.entity.LinkappFunction;
import com.easylinkin.linkappapi.function.service.LinkappFunctionService;
import com.easylinkin.linkappapi.openapi.dto.FunctionInfoDTO;
import com.easylinkin.linkappapi.openapi.dto.ProjectDTO;
import com.easylinkin.linkappapi.openapi.dto.TenantInfoDTO;
import com.easylinkin.linkappapi.personality.entity.Personality;
import com.easylinkin.linkappapi.personality.service.PersonalityService;
import com.easylinkin.linkappapi.ruleengine.service.RuleEngineService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappPrivilege;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.mapper.LinkappUserMapper;
import com.easylinkin.linkappapi.security.service.LinkappPrivilegeService;
import com.easylinkin.linkappapi.security.service.LinkappUserService;
import com.easylinkin.linkappapi.tenant.dto.LinkappTenantDTO;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.entity.TenantRefDeviceUnit;
import com.easylinkin.linkappapi.tenant.entity.TenantRefPrivilege;
import com.easylinkin.linkappapi.tenant.entity.TenantRefPrivilegeDTO;
import com.easylinkin.linkappapi.tenant.mapper.LinkappTenantMapper;
import com.easylinkin.linkappapi.tenant.sevice.LinkappTenantService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import site.morn.util.MessageDigestUtils;

import javax.annotation.Resource;
import java.util.*;

import static site.morn.constant.DigestConstant.Algorithms.SPRING_B_CRYPT;
/**
 * <p></p>
 *
 * @author liuming
 * @since 2020/4/14
 */
@Service
public class LinkappTenantServiceImpl extends ServiceImpl<LinkappTenantMapper, LinkappTenant> implements LinkappTenantService {
	
	private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(LinkappTenantServiceImpl.class);

	@Value("${linkapp.url}")
	private String url ;
	
	@Value("${linkapp.defaultPassword}")
	private String defaultPassword ;
	
	@Autowired
	private LinkappTenantMapper linkappTenantMapper ;
	
	@Autowired
	private LinkappUserService linkappUserService;
	
	@Autowired
	private ApplicationService applicationService;
	
	@Resource
	private LinkappUserContextProducer linkappUserContextProducer;
	
	@Resource
	private RuleEngineService ruleEngineService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Resource
	private EsBankServiceImpl eService;
	
	@Autowired
	private PersonalityService personalityService;
    
    @Autowired
    private DeviceUnitService deviceUnitService;
    
    @Autowired
    private LinkappPrivilegeService privilegeService;
    
    @Autowired
	LinkappFunctionService functionService;
    
    @Autowired
    LinkappUserMapper userMapper;
	
    @Override
	@Transactional(rollbackFor = Exception.class)
    public LinkappTenant addLinkappTenant(LinkappTenant linkappTenant) {
    		linkappTenant.setCreateTime(new Date());
    		QueryWrapper ew = new QueryWrapper();
        	ew.eq("app_key", linkappTenant.getAppKey());
        	Application application = applicationService.getOne(ew);
        	if(application!=null) {
        		linkappTenant.setPersonalityId(application.getPersonalityId());
        	}
        	checkLinkappTenantBeforeAdd(linkappTenant);
        	save(linkappTenant);
        	String username = checkUsername();
        	LinkappUser linkappUser = new LinkappUser();
        	String password = MessageDigestUtils.encrypt(SPRING_B_CRYPT, defaultPassword);
        	linkappUser.setUsername(username);
        	linkappUser.setNickname(username);
        	linkappUser.setPassword(password);
        	linkappUser.setTenantId(linkappTenant.getId());
        	linkappUser.setDisplay(true);
        	linkappUser.setLocked(false);
        	linkappUser.setCreateTime(new Date());
        	linkappUserService.add(linkappUser);
        	linkappTenant.setInitAccount(username);
        	if(application!=null) {
        		List<DeviceUnit> deviceUnitList = applicationService.selectDeviceUnitByApplication(application.getId());
            	List<LinkappPrivilege> privilegeList = applicationService.selectPrivilegeByApplication(application.getId());
            	this.tenant2DeviceUnits(linkappTenant, deviceUnitList);
            	TenantRefPrivilegeDTO tenantRefPrivilegeDTO = new TenantRefPrivilegeDTO();
            	tenantRefPrivilegeDTO.setPrivileges(privilegeList);
            	tenantRefPrivilegeDTO.setTenant(linkappTenant);
            	this.tenant2Privileges(tenantRefPrivilegeDTO);
        	}
        	return linkappTenant;
    }

	/**
	 * 在新增租户之前校验
	 */
	private void checkLinkappTenantBeforeAdd(LinkappTenant linkappTenant) {
//    	QueryWrapper qw = new QueryWrapper();
//    	qw.eq("project_id",linkappTenant.getProjectId());
//			Assert.isTrue(linkappTenantMapper.selectCount(qw) == 0, "已有重复的项目id");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public LinkappTenant initLinkappTenant(TenantInfoDTO tenantInfoDTO) {
		LinkappTenant linkappTenant = new LinkappTenant();
		linkappTenant.setAppId(tenantInfoDTO.getAppId());
		linkappTenant.setAppIndustryType(tenantInfoDTO.getAppIndustryType());
		linkappTenant.setAppKey(tenantInfoDTO.getAppkey());
		linkappTenant.setTenantId(tenantInfoDTO.getTenantId());
		linkappTenant.setProjectId(tenantInfoDTO.getProjectId());
		linkappTenant.setPlatformProjectName(tenantInfoDTO.getPlatformProjectName());
		linkappTenant.setPlatformAccount(tenantInfoDTO.getPlatformAccount());
		linkappTenant.setPlatformAccountName(tenantInfoDTO.getPlatformAccountName());
		if (tenantInfoDTO.getPersonality() != null && !tenantInfoDTO.getPersonality().isAllEmpty()) {
			Personality personality = tenantInfoDTO.getPersonality();
			personalityService.addPersonality(personality, tenantInfoDTO.getTenantId());
			linkappTenant.setPersonalityId(personality.getId());
		}
		linkappTenant.setCreateTime(new Date());
		QueryWrapper ew = new QueryWrapper();
		ew.eq("app_key", linkappTenant.getAppKey());
		Application application = applicationService.getOne(ew);
		save(linkappTenant);
		String username = checkUsername();
		LinkappUser linkappUser = new LinkappUser();
		String password = MessageDigestUtils.encrypt(SPRING_B_CRYPT, defaultPassword);
		linkappUser.setUsername(username);
		linkappUser.setNickname(username);
		linkappUser.setPassword(password);
		linkappUser.setTenantId(linkappTenant.getId());
		linkappUser.setDisplay(true);
		linkappUser.setLocked(false);
		linkappUser.setCreateTime(new Date());
		linkappUserService.add(linkappUser);
		linkappTenant.setInitAccount(username);
		if (tenantInfoDTO.getDeviceUnits() != null && !tenantInfoDTO.getDeviceUnits().isEmpty()) {
			List<DeviceUnit> deviceUnitList = new ArrayList<DeviceUnit>();
			for (com.easylinkin.linkappapi.openapi.dto.DeviceUnit du : tenantInfoDTO.getDeviceUnits()) {
				com.easylinkin.linkappapi.deviceunit.entity.DeviceUnit deviceUnit = new com.easylinkin.linkappapi.deviceunit.entity.DeviceUnit();
				deviceUnit.setCode(du.getCode());
				deviceUnit.setVersion(du.getDeviceVersion());
				deviceUnit = deviceUnitService.selectDeviceUnit(deviceUnit);
				if (deviceUnit != null) {
					deviceUnitList.add(deviceUnit);
				}
			}
			if (!deviceUnitList.isEmpty()) {
				this.tenant2DeviceUnits(linkappTenant, deviceUnitList);
			}
		}
		if (!tenantInfoDTO.getPrivileges().isEmpty()) {
			TenantRefPrivilegeDTO tenantRefPrivilegeDTO = new TenantRefPrivilegeDTO();
			List<LinkappPrivilege> privileges = tenantInfoDTO.getPrivileges();
			List<LinkappPrivilege> nodePrivileges = new ArrayList<LinkappPrivilege>();
			for(LinkappPrivilege privilege : privileges) {
				LinkappPrivilege privilegeQuery = new LinkappPrivilege();
				privilegeQuery.setParentId(privilege.getId());
				privilegeQuery.setType(2);
				List<LinkappPrivilege> privilegeQuerys = privilegeService.selectPrivilegeAll(privilegeQuery);
				if(!privilegeQuerys.isEmpty()) {
					nodePrivileges.addAll(privilegeQuerys);
				}
			}
			privileges.addAll(nodePrivileges);
			tenantRefPrivilegeDTO.setPrivileges(privileges);
			tenantRefPrivilegeDTO.setTenant(linkappTenant);
			this.tenant2Privileges(tenantRefPrivilegeDTO);
		}
		return linkappTenant;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public LinkappTenant initLinkappTenantByFunction(FunctionInfoDTO functionInfoDTO) {
		LinkappTenant linkappTenant = new LinkappTenant();
		linkappTenant.setAppId(functionInfoDTO.getAppId());
		linkappTenant.setAppIndustryType(functionInfoDTO.getAppIndustryType());
		linkappTenant.setAppKey(functionInfoDTO.getAppkey());
		linkappTenant.setTenantId(functionInfoDTO.getTenantId());
		linkappTenant.setProjectId(functionInfoDTO.getProjectId());
		linkappTenant.setPlatformProjectName(functionInfoDTO.getPlatformProjectName());
		linkappTenant.setPlatformAccount(functionInfoDTO.getPlatformAccount());
		linkappTenant.setPlatformAccountName(functionInfoDTO.getPlatformAccountName());
		if (null != functionInfoDTO.getProject()){
			ProjectDTO project = functionInfoDTO.getProject();
			//预计开工时间
			linkappTenant.setEstimateTime(project.getEstimateTime());
			//预计完工时间
			linkappTenant.setCompletionTime(project.getCompletionTime());
			//建设单位
			linkappTenant.setConstructionUnit(project.getConstructionUnit());
			//招标单位
			linkappTenant.setBiddingUnit(project.getBiddingUnit());
			//项目地点
			linkappTenant.setLocation(project.getLocation());
			linkappTenant.setProjectDesc(project.getProjectDesc());
			linkappTenant.setArea(project.getArea());
			//项目类型
			linkappTenant.setProjectType(project.getProjectType());
			//项目状态
			linkappTenant.setProjectStatus(project.getProjectStatus());
			//实际开工时间
			linkappTenant.setActualStartTime(project.getActualStartTime());
			//实际完工时间
			linkappTenant.setActualCompletionTime(project.getActualCompletionTime());
			//项目金额
			linkappTenant.setProjectAmount(project.getProjectAmount());
			//施工单位
			linkappTenant.setShigongUnit(project.getShigongUnit());
			//设计单位
			linkappTenant.setDesignUnit(project.getDesignUnit());
			//监理单位
			linkappTenant.setConstructionControlUnit(project.getConstructionControlUnit());
			//勘查单位
			linkappTenant.setExplorationUnit(project.getExplorationUnit());
			//项目区域
			linkappTenant.setProjectArea(project.getProjectArea());
			//质量创优等级
			linkappTenant.setQualityExcellenceLevel(project.getQualityExcellenceLevel());
			//安全创优等级
			linkappTenant.setSafetyExcellenceLevel(project.getSafetyExcellenceLevel());
			linkappTenant.setProjectManagerPhone(project.getProjectManagerPhone());
			linkappTenant.setProjectManager(project.getProjectManager());
			linkappTenant.setTechEngineer(project.getTechEngineer());
			linkappTenant.setTechEngineerPhone(project.getTechEngineerPhone());
			linkappTenant.setProductManager(project.getProductManager());
			linkappTenant.setProductManagerPhone(project.getProductManagerPhone());
			linkappTenant.setSafeExcellenceAward(project.getSafeExcellenceAward());
			linkappTenant.setQualityGoalAward(project.getQualityGoalAward());
		}
		if (functionInfoDTO.getPersonality() != null && !functionInfoDTO.getPersonality().isAllEmpty()) {
			Personality personality = functionInfoDTO.getPersonality();
			personality.setCreateTime(new Date());
			personalityService.addPersonality(personality, functionInfoDTO.getTenantId());
			linkappTenant.setPersonalityId(functionInfoDTO.getPersonality().getId());
		}
		linkappTenant.setCreateTime(new Date());
//		QueryWrapper ew = new QueryWrapper();
//		ew.eq("app_key", linkappTenant.getAppKey());
//		Application application = applicationService.getOne(ew);
		save(linkappTenant);
		String username = checkUsername();
		LinkappUser linkappUser = new LinkappUser();
		String password = MessageDigestUtils.encrypt(SPRING_B_CRYPT, defaultPassword);
		linkappUser.setUsername(username);
		linkappUser.setNickname(username);
		linkappUser.setPassword(password);
		linkappUser.setTenantId(linkappTenant.getId());
		linkappUser.setDisplay(true);
		linkappUser.setLocked(false);
		linkappUser.setCreateTime(new Date());
		linkappUserService.add(linkappUser);
		linkappTenant.setInitAccount(username);
		if (functionInfoDTO.getFunctions()!=null && !functionInfoDTO.getFunctions().isEmpty()) {
			List<LinkappFunction> functions = functionInfoDTO.getFunctions();
			//给租户分配功能模块
			functionService.functions2Tenant(linkappTenant.getId(), functions);
			TenantRefPrivilegeDTO tenantRefPrivilegeDTO = new TenantRefPrivilegeDTO();
			//给租户分配功能模块内的权限
			Set<LinkappPrivilege> privilegeSet = new HashSet<LinkappPrivilege>();
			for(LinkappFunction function : functions) {
				List<LinkappPrivilege> privilegeQuerys = functionService.selectPrivilegeByFunction(function.getId());
				privilegeSet.addAll(privilegeQuerys);
			}
			List<LinkappPrivilege> privileges = new ArrayList<LinkappPrivilege>();
			privileges.addAll(privilegeSet);
			tenantRefPrivilegeDTO.setPrivileges(privileges);
			tenantRefPrivilegeDTO.setTenant(linkappTenant);
			this.tenant2Privileges(tenantRefPrivilegeDTO);
		}
		return linkappTenant;
	}
	
    // 创建租户管理员帐号  admin@+5位随机数字   不足5位补0
    public String checkUsername() {
    	boolean loop = true;
    	String username = "admin@";
    	while(loop) {
    		int randomInt = (int)((Math.random()*99999));
        	String randomNo = String.format("%5d", randomInt).replace(" ", "0");
        	username = username + randomNo;
        	LOGGER.info("checkUsername:" + username);
        	LinkappUser linkappUser =  linkappUserService.findByUsername(username);
        	if(linkappUser == null) {
        		loop = false;
        	}else{
				username = "admin@";
			}
    	}
    	return username;
    }

	@Override
	public boolean updateLinkappTenant(LinkappTenant linkappTenant) {
		boolean updateById = this.updateById(linkappTenant);
		return updateById;
	}
	
	@Override
	public boolean tenant2Personality(LinkappTenant linkappTenant) {
		UpdateWrapper updateWrapper = new UpdateWrapper();
		updateWrapper.eq("id", linkappTenant.getId());
		updateWrapper.set("personality_id", linkappTenant.getPersonalityId());
		updateWrapper.set("modify_time", new Date());
		return this.update(updateWrapper);
	}

	@Override
	public List<LinkappTenant> selectLinkappTenantList(LinkappTenant linkappTenant) {
		return linkappTenantMapper.selectLinkappTenantList(linkappTenant);
	}
	
	@Override
	public IPage<LinkappTenant> selectLinkappTenantPage(Page page, LinkappTenant linkappTenant) {
		List<LinkappTenant> list = linkappTenantMapper.selectLinkappTenantList(page, linkappTenant);
		//管理平台端：租户状态0或null是正常，1是冻结
		page.setRecords(list);
		return page;
	}

	@Override
	public LinkappTenant selectLinkappTenant(LinkappTenant linkappTenant) {
		return linkappTenantMapper.selectLinkappTenant(linkappTenant);
	}

	@Override
	public String getSSOUrl(LinkappUser user) {
		Assert.notNull(user, "用户参数不能为空");
		Assert.hasLength(user.getUsername(), "用户名不能为空");
		Assert.hasLength(user.getPassword(), "用户名密码不能为空");
		LinkappUser linkappUser = linkappUserService.findByUsername(user.getUsername());
		Assert.notNull(linkappUser, "找不到该用户：" + user.getUsername());
		Assert.hasLength(linkappUser.getTenantId(), "用户没有对应的租户：" + user.getUsername());
//		判断查询到的用户是否和传递来的密码对应，不通过提示验证错误并返回
		boolean match = DigestUtil.bcryptMatches(user.getPassword(), linkappUser.getPassword());
		if (!match) {
			throw new BusinessException("密码不正确");
		}
		LinkappTenant linkappTenant = new LinkappTenant();
		linkappTenant.setId(linkappUser.getTenantId());
		return getSSOUrl(linkappTenant, user.getUsername());
	}

	@Override
	public String getSSOUrl(LinkappTenant linkappTenantQuery, String account) {
		LinkappTenant linkappTenant = linkappTenantMapper.selectLinkappTenant(linkappTenantQuery);
		if (linkappTenant == null) {
			return null;
		}
		LinkappUser linkappUser = linkappUserService.findByUsername(account);
		String uuid = UUID.randomUUID().toString();
		//设置有效时间5分钟
		redisUtil.set(uuid, linkappUser, 300);
//			 需要 优先返回个性化 url 如果没有个性化域名 返回平台应用的域名
		if (ObjectUtils.isNotEmpty(linkappTenant.getPersonalityId())) {
			Personality personality = personalityService.getById(linkappTenant.getPersonalityId());
			if (personality != null && ObjectUtils.isNotEmpty(personality.getDomin())) {
				return "http://" + personality.getDomin() + "/api/ssoLogin?ssoToken=" + uuid;
			}
		}
		return url + "/api/ssoLogin?ssoToken=" + uuid;
	}

	@Override
	public Map<String, String> getSSOUrl(String requestId, String appId, String tenantId, String id, String account, String headerSign, String appkey) {
		String signToString = requestId + "-" + tenantId + "-" + appId + "-" + id + "-" + account;
		LOGGER.info("headerSign : " + headerSign);
		LOGGER.info("signToString : " + signToString);
		LOGGER.info("appkey : " + appkey);
		QueryWrapper<Application> wrapper = new QueryWrapper<>();
		wrapper.eq("app_key", appkey);
		wrapper.eq("delete_state", 1);
		Application application = applicationService.getApplication(wrapper);
		//String sign = DigestUtil.hmacSHA256Sign(signToString,saasSecret).trim();
		String sign = DigestUtil.hmacSHA256Sign(signToString, application.getAppSecret()).trim();
		LOGGER.info("sign : " + sign);

		Map<String, String> map = new HashMap<>();
		if (sign.equalsIgnoreCase(headerSign)) {
			LinkappTenant linkappTenant = new LinkappTenant();
			linkappTenant.setTenantId(tenantId);
			linkappTenant.setAppId(appId);
			linkappTenant.setInitAccount(account);
//     		if(appType != null) {
//     			linkappTenant.setAppType(appType);
//     		}
			String ssoToken = getSSOUrl(linkappTenant, account);
			if (ssoToken == null) {
				map.put("code", "500");
				map.put("message", "获取失败");
			} else {
				map.put("code", "200");
				map.put("message", "success");
				map.put("ssoUrl", ssoToken);
			}
		} else {
			map.put("code", "501");
			map.put("message", "认证失败");
		}
		return map;
	}

  @Override
  public List<LinkappTenantDTO> selectUserTenantByPhone(String phone) {
		Assert.isTrue(StringUtils.isNotBlank(phone), "手机号不能为空");
		List<LinkappTenantDTO> userTanantLs = this.baseMapper.selectUserTenantByPhone(phone);
		return userTanantLs;
  }

	@Override
	public List<LinkappTenant> selectAll() {
		return this.baseMapper.selectAll();
	}

	@Override
	public List<LinkappTenantDTO> selectUserTenantByUser(LinkappUser user) {
		List<LinkappTenantDTO> userTanantLs = this.baseMapper.selectUserTenantByUser(user);
		return userTanantLs;
	}

    @Override
    public LinkappTenant getLastHasConfigOne() {
		LinkappTenant linkappTenant = linkappTenantMapper.getLastHasConfigOne();
		return linkappTenant;
    }

	@Override
	public LinkappTenant getOneByProjectId(Long projectId) {
		LinkappTenant linkappTenant = linkappTenantMapper.getOneByProjectId(projectId);
		return linkappTenant;
	}

    @Override
	public LinkappTenant currentTenant() {
		LinkappUser user = linkappUserContextProducer.getCurrent();
		if(user==null) {
			return null;
		}
		LinkappTenant linkappTenant = new LinkappTenant();
		linkappTenant.setId(user.getTenantId());
		return linkappTenantMapper.selectLinkappTenant(linkappTenant);
	}


	@Override
	public LinkappTenant getOneById(String id) {
		LinkappTenant linkappTenant = new LinkappTenant();
		linkappTenant.setId(id);
		return linkappTenantMapper.selectLinkappTenant(linkappTenant);
	}
	
	
	@Override
	public List<DeviceUnit> selectDeviceUnitByTenant(String id) {
		return linkappTenantMapper.selectDeviceUnitByTenant(id);
	}

	@Override
	public void tenant2DeviceUnits(LinkappTenant linkappTenant, List<DeviceUnit> deviceUnits) {
		linkappTenantMapper.deleteTenant2DeviceUnits(linkappTenant.getId());
		for(DeviceUnit deviceUnit :deviceUnits) {
			TenantRefDeviceUnit tenantRefDeviceUnit = new TenantRefDeviceUnit();
			tenantRefDeviceUnit.setTenantId(linkappTenant.getId());
			tenantRefDeviceUnit.setDeviceUnitId(deviceUnit.getId());
			tenantRefDeviceUnit.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			linkappTenantMapper.insertTenant2DeviceUnits(tenantRefDeviceUnit);
		}
	}

	@Override
	public List<LinkappPrivilege> selectPrivilegeByTenant(String id, Integer type) {
		return linkappTenantMapper.selectPrivilegeByTenant(id, type);
	}

	@Override
	public void tenant2Privileges(TenantRefPrivilegeDTO tenantRefPrivilegeDTO) {
		LinkappTenant linkappTenant = tenantRefPrivilegeDTO.getTenant();
		List<LinkappPrivilege> privileges = tenantRefPrivilegeDTO.getPrivileges();
		List<LinkappPrivilege> delPrivileges = tenantRefPrivilegeDTO.getDelPrivileges();
		linkappTenantMapper.deleteTenant2Privileges(linkappTenant.getId(), tenantRefPrivilegeDTO.getType());
		if(privileges!=null && !privileges.isEmpty()) {
			for(LinkappPrivilege privilege :privileges) {
				TenantRefPrivilege tenantRefPrivilege = new TenantRefPrivilege();
				tenantRefPrivilege.setTenantId(linkappTenant.getId());
				tenantRefPrivilege.setPrivilegeId(privilege.getId().toString());
				tenantRefPrivilege.setId(UUID.randomUUID().toString().replaceAll("-", ""));
				linkappTenantMapper.insertTenant2Privileges(tenantRefPrivilege);
			}
		}
		if(delPrivileges!=null&&!delPrivileges.isEmpty()) {
			for(LinkappPrivilege delPrivilege :delPrivileges) {
				baseMapper.deleteRole2Privileges(delPrivilege.getId().toString(), linkappTenant.getId());
			}
		}
		
	}

	@Override
	public List<LinkappPrivilege> selectTenantPrivilegeByUser(String id) {
		return linkappTenantMapper.selectTenantPrivilegeByUser(id, 0);
	}


	@Override
	public List<DeviceUnit> selectTenantDeviceUnitByUser(String id) {
		return linkappTenantMapper.selectTenantDeviceUnitByUser(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean unlockTenant(String id) {
		try {
			UpdateWrapper<LinkappTenant> updateWrapper = new UpdateWrapper<LinkappTenant>();
			updateWrapper.eq("id", id);
			updateWrapper.set("status", 1);
			this.update(updateWrapper);
			userMapper.tenantUnLock(id);
			ruleEngineService.enableByTenantId(id);
			return true;
		}
		catch(Exception e) {
			return false;
		}
	}

	@Override
	public boolean lockTenant(String id) {
//		2021-08-28 租户管理列表冻结后不在删除租户数据，只锁定用户数据
		/*UpdateWrapper<LinkappTenant> updateWrapper = new UpdateWrapper<LinkappTenant>();
		updateWrapper.eq("id", id);
//			逻辑删除
		updateWrapper.set("status", 0);
		this.update(updateWrapper);*/
		userMapper.tenantLock(id);
		ruleEngineService.disableByTenantId(id);
		return true;
	}
	
}
